package com.ruofeng.app.kotlin.common.dsl.library

import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.Test

/**
 * Created by 邱鹏 on 2017/8/25.
 */
open class LibraryTest {
    class LibraryBuilder {
        var library = Library()
        var address: String = ""
            set(value) {
                library.address = value
            }

        fun bookShelf(init: BookShelfBuilder.() -> Unit): Unit {
            var builder = BookShelfBuilder().apply(init)
            library.bookShelf = builder.bookShelf
        }
    }

    class BookShelfBuilder {
        var bookShelf = BookShelf()
        var name: String? = ""
            set(value) {bookShelf.name=value}
        var serialNum: String? = ""
        fun book(init: Book.() -> Unit) {
            bookShelf.book = Book().apply(init)
        }
    }

    fun buildLibrary(buildAction: LibraryBuilder.() -> Unit): Library {
        val builder = LibraryBuilder()
        builder.buildAction()
        return builder.library
    }

    @Test
    fun testResult() {
        val result = buildLibrary {
            address = "地址"
            bookShelf {
                name = "书架"
                book {
                    name = "书名"
                    author = "南怀瑾老师"
                    chapter = null
                }
            }
        }
        println(ObjectMapper().writeValueAsString(result))
    }
}